/***************************************************************************
 *
 * Copyright (c) 2012 Baidu.com, Inc. All Rights Reserved
 * common.h,v 1.0 2012-09-01 15:58 yelu01
 *
 **************************************************************************/



/**
 * @file item.cpp
 * @author yelu01(yelu01@baidu.com)
 * @date 2012-09-01 15:58
 * @version 1.0
 * @brief matrix item.
 *
 **/

#include "item.h"
#include "log.h"
#include "check_macro.h"

item_t::item_t()
{
	timestamp = 0;
	del = false;
}

uint64_t item_t::size()
{
	return row.size() + col.size() + value.size();
}

uint64_t item_t::serialize(FILE* fp)
{
	uint64_t total_len = 0;
	// write index_key.
	uint64_t len = row.serialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to serialize index key.");
	total_len += len;
	// write extra_key.
	len = col.serialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to serialize extra key.");
	total_len += len;
	// write version.
	len = fwrite(&timestamp, sizeof(timestamp), 1, fp);
	CHECK_TRUE(len == 1, return 0, "failed to serialize timestamp.");
	total_len += (sizeof(timestamp) * len);
	// write del.
	len = fwrite(&del, sizeof(del), 1, fp);
	CHECK_TRUE(len == 1, return 0, "failed to serialize del.");
	total_len += (sizeof(del) * len);
	// write value.
	len = value.serialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to serialize value.");
	total_len += len;
	return total_len;
}

uint64_t item_t::deserialize(FILE* fp)
{
	uint64_t total_len = 0;
	// read index_key.
	uint64_t len = row.deserialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to deserialize index key.");
	total_len += len;
	// read extra_key.
	len = col.deserialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to deserialize extra key.");
	total_len += len;
	// read del.
	len = fread(&timestamp, sizeof(timestamp), 1, fp);
	CHECK_TRUE(len == 1, return 0, "failed to deserialize timestamp.");
	total_len += (sizeof(timestamp) * len);
	// read del.
	len = fread(&del, sizeof(del), 1, fp);
	CHECK_TRUE(len == 1, return 0, "failed to deserialize del.");
	total_len += (sizeof(del) * len);
	// read value.
	len = value.deserialize(fp);
	CHECK_TRUE(len > 0, return 0, "failed to deserialize value.");
	total_len += len;
	return total_len;
}

